"""
自定义的分页组件。若使用，需要做以下几件事：
    def pretty_list(request):
        # 1、根据情况筛选需要的数据queryset
        queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
        # 实例化分页对象
        page_obj = MyPagination(request,contents,page_param="page",page_size=7,plus=2)
        # 分页后返回的数据
        context = {
            "postlist": page_obj.postlist,             # 分完页后的数据
            "page_string": page_obj.html_page()       # 生成页码
        }
        return render(request,'xxx.html',context)

    # 分页显示
    <ul  class="pagination">
        {{page_string}}
    </ul>
"""

import copy
from django.core.paginator import Paginator
from django.utils.safestring import mark_safe


class MyPagination(object):
    def __init__(self,request,contents,page_param="page",page_size=7,plus=2):
        """
        :params  request：请求的对象
        :params  queryset：符合条件的数据（根据这个数据进行分页处理）
        :params  page_param：在url中传递的获取分页的参数，例如：/pretty/list/?page=12
        :params  page_size：每页显示多少条数据
        :params  plus：显示当前页的前后几页（页码）
        """
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict
        self.page_param = page_param
        page = request.GET.get(self.page_param, '1')
        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        self.page = page

        page_obj = Paginator(contents, page_size)
        self.postlist = page_obj.page(self.page)  # 每一页的内容
        # print("self.postlist: ",type(self.postlist),len(self.postlist),self.postlist)
        # for post in self.postlist:
        #     # print("post:",post,type(post))
        #     print(post['id'],post['title'],post['created'])
        self.page_counts = page_obj.num_pages      # 总页数
        self.plus = plus
        # 呈现的所有页码
        self.pagelist = list(page_obj.get_elided_page_range(number=self.page, on_each_side=2, on_ends=2))
        # print("self.page: ",self.page,"self.page_counts: ",self.page_counts)

    def html_page(self):
        # 在浏览器上显示页码
        page_str_list = []
        if self.page == 1 and len(self.pagelist) == 1:
            return ''
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [1])
            page_str_list.append(f"<a href='?{self.query_dict.urlencode()}' style='margin-left:350px'>首页</a>&emsp;")
            self.query_dict.setlist(self.page_param, [self.page - 1])
            page_pre = f"<a href='?{self.query_dict.urlencode()}'>上一页</a>&emsp;"
            page_str_list.append(page_pre)
        for i in self.pagelist:
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = f"<span style='margin-left:350px'>{i}</span>&emsp;"
            else:
                ele = f"<a href='?{self.query_dict.urlencode()}'>{i}</a>&emsp;"
            page_str_list.append(ele)
        if self.page < self.page_counts:
            self.query_dict.setlist(self.page_param, [self.page + 1])
            page_after = f"<a href='?{self.query_dict.urlencode()}'>下一页</a>&emsp;"
            page_str_list.append(page_after)
            self.query_dict.setlist(self.page_param, [self.page_counts])
            page_str_list.append(f"<a href='?{self.query_dict.urlencode()}'>尾页</a>&emsp;")
        page_string = mark_safe("".join(page_str_list))  # html格式在浏览器上转为显示内容
        return page_string